<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>

<script lang="ts" setup>
defineOptions({
	name: "device-kind",
});

import { useCrud, useTable, useUpsert, useSearch } from "@cool-vue/crud";
import { useCool } from "/@/cool";
import { useI18n } from "vue-i18n";
import { useDict } from '/$/dict';

const { service } = useCool();
const { t } = useI18n();

const { dict } = useDict();

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			label: t("所属大类"),
			prop: "category",
			component: { name: "el-select", options: dict.get("classification"), },
			span: 24,
		},
		{
			label: t("设备型号"),
			prop: "name",
			component: { name: "el-input", props: { clearable: true } },
			span: 24,
		},
		{
			label: t("设备连接方式"),
			prop: "methods",
			component: { name: "el-select", options: dict.get("connection"), props: { multiple: true } },
			span: 24,

		},
		{
			label: t("设备图标"),
			prop: "icon",
			component: { name: "cl-upload", props: { clearable: true } },
			span: 24,
		},

	],
	onSubmit(data, { done, close, next }) {


		next({
			...data,
			methods: data.methods.join(","),
		});
		close();

	},
});

const _opts = dict.get('connection');

// cl-table
const Table = useTable({
	columns: [
		{ type: "selection" },
		{ label: t("设备名称"), prop: "name", minWidth: 120 },
		{
			// 1 wifi、2 4g、3 蓝牙、4 lora，支持多个
			label: t("设备连接方法"), prop: "methods", minWidth: 120, render(row, column, value, index) {
				// row.methods是一个字符串，需要转换成数组
				return row.methods.split(",").map((item) => {
					return _opts?.value?.find(v => v.value == item)?.label
				}).join(" / ");

				// return row.methods.map((item) => {
				// 	return item.name;
				// }).join(",");
			},
		},
		{ label: t("设备图标"), prop: "icon", minWidth: 120 },
		{ label: t("所属大类"), prop: "category", minWidth: 120, dict: dict.get("classification") },
		{ type: "op", buttons: ["edit", "delete"] },
	],
});

// cl-search
const Search = useSearch();

// cl-crud
const Crud = useCrud(
	{
		service: service.device.kind,
	},
	(app) => {
		app.refresh();
	},
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
</script>
